//
//  LGNickLabel.m
//  LGNickLabel
//
//  Created by lg on 29/10/2019.
//  Copyright © 2019 lg. All rights reserved.
//

#import "LGNickLabel.h"
#import <YYText/YYText.h>

@interface LGNickLabel ()

@property(nonatomic) YYLabel *nickNameLabel;
@property(nonatomic) UIView *badgeStackView;
@property(nonatomic) UIView *truncationView;
@property(nonatomic) UIView *truncationBadgeStackView;
@property(nonatomic) UILabel *truncationLabel;

@end

@implementation LGNickLabel

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        [self setup];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setup];
    }
    return self;
}

- (void)setup {
    _font = self.nickNameLabel.font;
    _imageViewSize = CGSizeMake(18,18);
    _space = 2;
    _imageViewSpace = 2;

    [self addSubview:self.nickNameLabel];
    
    [self.truncationView addSubview:self.truncationLabel];
    [self.truncationView addSubview:self.truncationBadgeStackView];
    
    
}
#pragma mark - Override
- (void)layoutSubviews {
    CGSize size = self.bounds.size;
    
    [self.nickNameLabel setFrame:CGRectMake(0, 0, size.width, size.height)];
    [self layoutTruncationView];
    [self layoutBadgeStackView];
}

- (void)setBackgroundColor:(UIColor *)backgroundColor {
    [self.nickNameLabel setBackgroundColor:backgroundColor];
    [self.truncationLabel setBackgroundColor:backgroundColor];
}

// 如果是通过 auto layout 布局子视图，则需要实现这个方法，并且返回 YES
//+ (BOOL)requiresConstraintBasedLayout {
//    return YES;
//}
#pragma mark - private

/// 计算 StackView 尺寸
- (CGSize)calculateStackViewSize {
    /*
     |--space--imageView--imageViewSpace--imageView--|
     */
    CGSize stackViewSize = CGSizeMake(0, self.font.lineHeight);
    
    if (self.images.count == 0) {
        stackViewSize.width = 0;
    } else {
        stackViewSize.width = self.images.count * (self.imageViewSize.width + self.imageViewSpace) - self.imageViewSpace + self.space;
    }
    return stackViewSize;
}

/// 调整 truncationView 布局
- (void)layoutTruncationView {
    CGSize stackViewSize = [self calculateStackViewSize];
    [self.truncationBadgeStackView setBounds:CGRectMake(0, 0, stackViewSize.width, stackViewSize.height)];
    
    // 布局文本截断内容
    [self.truncationLabel setFont:self.font];
    [self.truncationLabel setTextColor:self.textColor];
    [self.truncationLabel sizeToFit];
    
//    NSLog(@"label height = %f", self.truncationLabel.bounds.size.height);
//    NSLog(@"line height %f", self.truncationView.bounds.size.height);
    
    [self.truncationView setBounds:CGRectMake(0, 0, self.truncationBadgeStackView.bounds.size.width+self.truncationLabel.bounds.size.width, self.truncationBadgeStackView.bounds.size.height)];
    [self.truncationLabel setCenter:CGPointMake(self.truncationLabel.bounds.size.width/2, self.truncationBadgeStackView.bounds.size.height/2)];
    [self.truncationBadgeStackView setCenter:CGPointMake(self.truncationView.bounds.size.width-self.truncationBadgeStackView.bounds.size.width/2, self.truncationView.bounds.size.height/2)];
}

/// 调整 badgeStackView 布局
- (void)layoutBadgeStackView {
    CGSize stackViewSize = [self calculateStackViewSize];
    [self.badgeStackView setBounds:CGRectMake(0, 0, stackViewSize.width, stackViewSize.height)];
}

/// 设置 nicklabel 文本
- (void)setupNickLabelText {
    
    // 创建文本截断内容
    NSMutableAttributedString *truncationAttachment = [NSMutableAttributedString yy_attachmentStringWithContent:self.truncationView contentMode:UIViewContentModeCenter attachmentSize:self.truncationView.bounds.size alignToFont:self.nickNameLabel.font alignment:YYTextVerticalAlignmentCenter];
    [truncationAttachment setYy_font:self.font];
    [truncationAttachment setYy_color:self.textColor];
    
    self.nickNameLabel.truncationToken = truncationAttachment;
    
    // 创建徽章内容
    NSMutableAttributedString *attachment = [NSMutableAttributedString yy_attachmentStringWithContent:self.badgeStackView contentMode:UIViewContentModeCenter attachmentSize:self.badgeStackView.bounds.size alignToFont:self.nickNameLabel.font alignment:YYTextVerticalAlignmentCenter];
    [attachment setYy_font:self.font];
    [attachment setYy_color:self.textColor];
    
    // 创建整体文本
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:self.text ? self.text : @""];
    [text appendAttributedString:attachment];
    [text setYy_font:self.font];
    [text setYy_color:self.textColor];
    text.yy_alignment = self.textAlignment;
    
    self.nickNameLabel.attributedText = text;
}

- (void)layoutAndConfigImageView {
    __weak typeof(self) weakSelf = self;
    [self.badgeStackView.subviews enumerateObjectsUsingBlock:^(UIImageView * _Nonnull v, NSUInteger idx, BOOL * _Nonnull stop) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        // TODO:设置图片
        NSString *imageUrlOrName = strongSelf.images[idx];
        if (strongSelf.configImageBlock) {
            strongSelf.configImageBlock(v, idx, imageUrlOrName);
        } else {
            [v setImage:[UIImage imageNamed:strongSelf.images[idx]]];
        }
        
        [v setBounds:CGRectMake(0, 0, strongSelf.imageViewSize.width, strongSelf.imageViewSize.height)];
        [v setCenter:CGPointMake(idx*(strongSelf.imageViewSize.width+strongSelf.imageViewSpace)+strongSelf.space+strongSelf.imageViewSize.width/2, strongSelf.badgeStackView.bounds.size.height/2)];
        
        v.tag = idx;
    }];
    
    [self.truncationBadgeStackView.subviews enumerateObjectsUsingBlock:^(UIImageView * _Nonnull v, NSUInteger idx, BOOL * _Nonnull stop) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        // TODO:设置图片
        NSString *imageUrlOrName = strongSelf.images[idx];
        if (strongSelf.configImageBlock) {
            strongSelf.configImageBlock(v, idx, imageUrlOrName);
        } else {
            [v setImage:[UIImage imageNamed:strongSelf.images[idx]]];
        }
        
        [v setBounds:CGRectMake(0, 0, strongSelf.imageViewSize.width, strongSelf.imageViewSize.height)];
        [v setCenter:CGPointMake(idx*(strongSelf.imageViewSize.width+strongSelf.imageViewSpace)+strongSelf.space+strongSelf.imageViewSize.width/2, strongSelf.truncationBadgeStackView.bounds.size.height/2)];
        
        v.tag = idx;
    }];
}
#pragma mark - LGNickLabel

- (void)setFont:(UIFont *)font {
    _font = font;
    // 影响布局
    [self layoutBadgeStackView];
    [self layoutTruncationView];
    [self setupNickLabelText];
}

- (void)setTextColor:(UIColor *)textColor
{
    _textColor = textColor;
    [self setupNickLabelText];
}

- (void)setText:(NSString *)text{
    _text = [text copy];
    [self setupNickLabelText];
}

- (void)setNumberOfLines:(NSInteger)numberOfLines {
    _numberOfLines = numberOfLines;
    self.nickNameLabel.numberOfLines = numberOfLines;
}

- (void)setTextAlignment:(NSTextAlignment)textAlignment {
    _textAlignment = textAlignment;
    self.nickNameLabel.textAlignment =  textAlignment;
}

- (void)setConfigImageBlock:(LGNickLabelConfigImageBlock)configImageBlock {
    _configImageBlock = [configImageBlock copy];

    if (self.images.count > 0) {
        [self layoutAndConfigImageView];
        [self layoutBadgeStackView];
        [self layoutTruncationView];
        [self setupNickLabelText];
    }
}

- (void)setImages:(NSArray<NSString *> *)images {
    _images = images;
    while (self.badgeStackView.subviews.count < _images.count) {
        [self.badgeStackView addSubview:[self getImageView]];
    }
    while (self.badgeStackView.subviews.count > _images.count) {
        [self.badgeStackView.subviews.lastObject removeFromSuperview];
    }
    
    while (self.truncationBadgeStackView.subviews.count < _images.count) {
        [self.truncationBadgeStackView addSubview:[self getImageView]];
    }
    while (self.truncationBadgeStackView.subviews.count > _images.count) {
        [self.truncationBadgeStackView.subviews.lastObject removeFromSuperview];
    }
    
    [self layoutAndConfigImageView];
    [self layoutBadgeStackView];
    [self layoutTruncationView];
    [self setupNickLabelText];
}

- (void)setSpace:(CGFloat)space {
    _space = space;
    [self layoutBadgeStackView];
    [self layoutTruncationView];
    [self layoutAndConfigImageView];
    [self setupNickLabelText];
}

- (void)setImageViewSpace:(CGFloat)imageViewSpace {
    _imageViewSpace = imageViewSpace;
    [self layoutBadgeStackView];
    [self layoutTruncationView];
    [self layoutAndConfigImageView];
    [self setupNickLabelText];
}

- (void)setImageViewSize:(CGSize)imageViewSize {
    _imageViewSize =imageViewSize;
    [self layoutAndConfigImageView];
    [self layoutBadgeStackView];
    [self layoutTruncationView];
    [self setupNickLabelText];
}

#pragma mark - Lazy
- (YYLabel *)nickNameLabel {
    if (!_nickNameLabel) {
        _nickNameLabel = [[YYLabel alloc] init];
//        [_nickNameLabel setDisplaysAsynchronously:YES];
    }
    return _nickNameLabel;
}
- (UIView *)badgeStackView {
    if (!_badgeStackView) {
        _badgeStackView = [[UIView alloc] init];
    }
    return _badgeStackView;
}
- (UIView *)truncationView {
    if (!_truncationView) {
        _truncationView = [[UIView alloc] init];
    }
    return _truncationView;
}
- (UIView *)truncationBadgeStackView {
    if (!_truncationBadgeStackView) {
        _truncationBadgeStackView = [[UIView alloc] init];
    }
    return _truncationBadgeStackView;
}
- (UILabel *)truncationLabel {
    if (!_truncationLabel) {
        _truncationLabel = [[UILabel alloc] init];
        [_truncationLabel setText:@"..."];
    }
    return _truncationLabel;
}
#pragma mark -
- (UIImageView *)getImageView {
    UIImageView *a = [[UIImageView alloc] init];
    [a setContentMode:UIViewContentModeScaleAspectFill];
    [self addTapHandleToImageView:a];
    return a;
}

- (void)addTapHandleToImageView:(UIImageView *)imageView {
    [imageView setUserInteractionEnabled:YES];
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onClickImage:)];
    [imageView addGestureRecognizer:singleTap];
}

- (void)onClickImage:(UITapGestureRecognizer *)recognizer {
    if (self.delegate && [self.delegate respondsToSelector:@selector(nickLabel:didClickWithIndex:)]) {
        [self.delegate nickLabel:self didClickWithIndex:recognizer.view.tag];
    }
}

@end
